package com.example.demo.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.example.demo.enums.RedisPreEnum;
import com.example.demo.mapper.MqttDataMapper;
import com.example.demo.mapper.MqttPublishDataMapper;
import com.example.demo.entity.MqttData;
import com.example.demo.entity.MqttPublishData;
import com.example.demo.service.MqttService;
import com.example.demo.utils.DateToStamp;
import com.example.demo.utils.MqttUtils;
import com.example.demo.utils.RedisUtil;
import com.example.demo.utils.UnicodeUtils;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class MqttServiceImpl implements MqttService {

    @Resource
    MqttDataMapper mqttMapper;
    @Resource
    MqttPublishDataMapper mqttPublishDataMapper;
    @Resource
    private RedisUtil redisUtil;

    @Resource
    private RedisTemplate<String, Object> redisTemplate;


    /**
     * 连接mqtt服务，暂时废弃
     *
     * @param id
     */
    @Override
    public void connect(int id) {
        MqttData mqttData = mqttMapper.selectOneById(id);
        try {
            MqttClient mqttClient = MqttUtils.mqttConnect(mqttData.getHost(), mqttData.getClientId(), mqttData.getSubscribeTopic());
            String key = RedisPreEnum.MQTT_CONNECT.getPre() + mqttData.getId();
            Long time = 7200L;
            redisUtil.setT(key, JSONObject.toJSONString(mqttClient), time);
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }

    /**
     * 新增mqtt连接数据
     *
     * @param mqttData
     */
    @Override
    public void addMqttData(MqttData mqttData) {
        mqttData.setCreateTime(DateToStamp.getTimeStamp());
        mqttData.setUpdateTime(DateToStamp.getTimeStamp());
        mqttMapper.insert(mqttData);
    }

    /**
     * 新增mqtt发布消息所需数据，且与mqtt连接数据关联
     *
     * @param mqttPublishData
     */
    @Override
    public void addMqttPublishData(MqttPublishData mqttPublishData) {
        mqttPublishData.setCreateTime(DateToStamp.getTimeStamp());
        mqttPublishData.setUpdateTime(DateToStamp.getTimeStamp());
        mqttPublishDataMapper.insert(mqttPublishData);
    }

    /**
     * mqtt推送实现，且返回结果
     *
     * @param id
     * @return
     */
    @Override
    public String publish(int id) {
        MqttData mqttData = mqttMapper.selectOneById(id);
        MqttPublishData mqttPublishData = mqttPublishDataMapper.selectOneByMqttDataId(mqttData.getId());
        String key = RedisPreEnum.MQTT_CONNECT.getPre() + mqttData.getId();
        String getBackMessage = null;
        try {
            //每次都需要连接一下mqtt服务，订阅主题 麻烦 后期重新定义开发
            MqttClient mqttClient = MqttUtils.mqttConnect(mqttData.getHost(), mqttData.getClientId(), mqttData.getSubscribeTopic());
            //发布mqtt消息至发布主题
            MqttUtils.mqttPublish(mqttClient, mqttData.getPublishTopic(), mqttPublishData.getPublishData());
//            mqttClient.close();
            System.out.println("返回结果：" + mqttClient.isConnected());
            int num = 0;
            //判断服务器是否返回结果，且循环1分钟，没有返回结果，则返回空
            while (getBackMessage == null && num <= 5) {
                Thread.sleep(200);
                //获取订阅主题回调内容，空则进入循环等待获取
                getBackMessage = MqttUtils.getCaLLBackMessage();
//                System.out.println("返回getBackMessage结果："+getBackMessage);
                num += 1;
//                System.out.println("循环次数:"+num);
            }
            if (getBackMessage == null) {
                getBackMessage = "未获取到返回结果，请重试";
            } else {
                getBackMessage = UnicodeUtils.unicodeToCn(getBackMessage);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return getBackMessage;
    }
}
